package com.weavernorth.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

/**
 * @Author: bruseewang
 * @Package: com.weavernorth.util
 * @date: 2021/8/23 11:26
 * @description: 文件上传工具
 */
public class FileUploadUtil{
    private static final long serialVersionUID = 1L;
    //上传配置
    //设置内存临界值(内存缓冲区)：用于将文件保存在内存还是磁盘临时文件夹的临界值
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;  // 3MB
    //设置最大文件上传值
    public static int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB

    /***
     * 文件上传
     * @param uploadPath 上传路径
     * @param request
     * @param log 日志类
     * @return 上传结果
     */
    public static String upload(String uploadPath, HttpServletRequest request, Logger log) {
        String strMessage = "0|文件上传成功！";
        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录：/tmp
        String tempPath = System.getProperty("java.io.tmpdir");
        log.info("临时存储目录：" + tempPath);
        factory.setRepository(new File(tempPath));
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 设置最大文件上传值
        upload.setSizeMax(MAX_FILE_SIZE);
        // 中文处理
        upload.setHeaderEncoding("UTF-8");
        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录
        //String uploadPath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;
        log.info("文件存储路径：" + uploadPath);
        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        try {
            // 解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        log.info("文件名：" + fileName);
                        String prefix = UUID.randomUUID().toString();
                        log.info("文件前缀：" + prefix);
                        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                        log.info("文件后缀：" + suffix);
                        fileName = prefix + "." + suffix;
                        log.info("文件名new：" + fileName);
                        String filePath = uploadPath + File.separator + fileName;
                        log.info("文件上传路径：" + filePath);
                        File storeFile = new File(filePath);
                        // 保存文件到硬盘
                        item.write(storeFile);
//                        request.setAttribute("message",
//                                "文件上传成功!");
                    }
                }
            }
        } catch (Exception ex) {
            log.info("上传异常,异常信息：" + ex.getMessage());
            strMessage = "1|上传异常,异常信息：" + ex.getMessage();
//            request.setAttribute("message",
//                    "错误信息: " + ex.getMessage());
        } finally {
            return strMessage;
        }
    }

    /**
     * 判断文件大小
     *
     * @param file 文件
     * @param size 限制大小
     * @param unit 限制单位（B,K,M,G）
     * @return
     */
    public static boolean checkFileSize(File file, int size, String unit) {
        long len = file.length();
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        BigDecimal a=new BigDecimal(fileSize);
        BigDecimal b=new BigDecimal(size);
        //如果上传文件大于限制的大小,则返回true
        if(a.compareTo(b)==1){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 判断文件大小
     *
     * @param fileLen 文件大小
     * @param maxSize 限制大小
     * @param unit 限制单位（B,K,M,G）
     * @return
     */
    public static boolean checkFileSize(int fileLen, int maxSize, String unit) {
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) fileLen;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) fileLen / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) fileLen / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) fileLen / 1073741824;
        }
        BigDecimal a=new BigDecimal(fileSize);
        BigDecimal b=new BigDecimal(maxSize);
        //如果上传文件大于限制的大小,则返回true
        if(a.compareTo(b)==1){
            return true;
        }else{
            return false;
        }
    }


}
